<?php
// +----------------------------------------------------------------------
// | EtrolPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Author: Author: LJQ <245369209@qq.com> 
// +----------------------------------------------------------------------

namespace app\admin\controller\api;
use app\common\controller\Api;
use think\response\Json;
/**
 * 用户权限
 * @package app\enterprise
 */
class Rule extends Api

{

    /**
   * 权限列表
   * 
   * @return  json 
   * 
   *
   */

	public function ruleList(){
             $model = model('common/Rule');
			if(($limit = input('limit')) && ($page = input('page'))){
					$startLimit =  ($page-1)*$limit;
					//企业列表
					$list =collection(model('Rule')->order('path')->limit($startLimit.','.$limit)->select())->toArray();
			}else{
					//企业列表
					$list =collection(model('Rule')->order('path')->select())->toArray();
			}
            foreach ($list as $key => $value) { 
                    $a = $value['level']?'|':'';
                    $b = str_repeat('---',$value['level']);
                    $list[$key]['title'] = $a.$b.$value['title'];
            }
            $count = $model->count('id');
            if ($list) {
                   return json(['code'=>1,'msg'=>'权限列表','count'=>$count,'data'=>$list]);
            }else{
                   return json(['code'=>0,'msg'=>'数据异常,请检查','count'=>$count]);
            }
    }
   	  
  /**
   * 添加权限
   * 
   * @return  json 
   * @param array data 表单数据,
   *
   */
   	 public function add($data=null){
       $model = model('common/Rule');
         if (empty($data)) {
              return json(['code'=>0,'msg'=>'数据异常,请检查']);
          }

        
              // if ($validate->check($data)) {
                   $result =$model->insertGetId($data);
                      if ($result !== false) {
                          //处理path字段
                            if ($data['pid'] == 0) {
                             //一级菜单  path为自己
                              $path = $result;
                            }else{
                             $parent=$model->where(array('id'=>$data['pid']))->value('path');
                             $path = $parent."-".$result;
                            }
                             //等级
                           $level = substr_count($path,'-');
                             //添加path和level
                            if($model->where(array('id'=>$result))->update(['path'=>$path,'level'=>$level])!== false){
                              setlog('Ruleadd','Rule',session('user_auth.id'));
                              return json(['code'=>1,'msg'=>'权限添加成功']);
                            }else{

                                return json(['code'=>0,'msg'=>'权限添加失败,请检查']);
                            }
                      }

              
                  
             // else{
             //  $list=$model->order(array('path'=>'ASC'))->select();
             //  $options=" <option value='0'>请选择上级分类(不选为顶级分类)</option>";
             //  foreach ($list as  $v) {
             //  $options.= "<option value=".$v['id'].">".($v['level']?'|':' ').(str_repeat('---',$v['level'])).$v['title']."</option>";
             //   }
             // return json(['code'=>1,'msg'=>'权限下拉列表','data'=>$options]);
             // }
}


   	
   /**
   * 修改权限
   * @param string ruleId 权限id,data修改的权限数据
   * @return json
   *
   */
   	public function edit($data=null,$ruleId=null){
          
          if (empty($ruleId)) {
              return json(['code'=>0,'msg'=>'权限不存在,请检查']);
          }

          $model = model('common/Rule');

          if(!empty($data)) {
              // $validate = validate('admin/Rule');
              // if($validate->check($data)){
                  //先清除path字段
                    $model->where(array('id'=>$ruleId))->setField('path','');
                       //处理path字段
                    if($data['pid'] == 0){
                        //一级菜单  path为自己
                        $data['path'] = $ruleId;
                    }else{
                        $parent=$model->where(array('id'=>$data['pid']))->value('path');
                        $data['path'] = $parent."-".$ruleId;
                    }
                     //等级
                    $data['level'] = substr_count($data['path'],'-');
                    //修改菜单
                    if($model->where(array('id'=>$ruleId)) ->update($data)!== false){
                       setlog('Ruleupdate','Rule',session('user_auth.id'));
                        //更新path字段
                         return json(['code'=>1,'msg'=>'权限修改成功']);
                    }else{
                        return json(['code'=>0,'msg'=>'权限修改失败,请检查']);
                    }

                }
        // }
        // else{
        //   $rule=$model->where(array('id'=>$ruleId))->find();
           
        //   $list = $model->order(array('path'=>'ASC'))->select();
        //     $options=" <option value='0'>请选择上级分类(不选为顶级分类)</option>";
        //       foreach ($list as  $v) {
        //          $select=($rule['pid']==$v['id']?'select="selected"':' ');
        //        $options.= "<option value=".$v['id'].$select."|default =' '>".($v['level']?'|':' ').(str_repeat('---',$v['level'])).$v['title']."</option>";
        //         }
        //      return json(['code'=>1,'msg'=>'权限下拉列表','data'=>$options]);
        // }
   }

   	 
     
    /**
   *  删除权限
   * @param  string ruleid 权限id,
   * @return  json
   *
   */
     
    public function del() {
            $ruleId = input('ruleId',0,'intval');
            if (empty($ruleId)) {
               return  json(['code' => 0,'msg' => '权限id不存在,请检查']);
            }
            $model =  model('common/Rule'); 
            if ($ruleId) {
               $count = $model->where(array('pid' => $ruleId ))->count();
               if ($count > 0) {
                 return $this->json(['code' => 0,'msg' => '该权限下还有子权限,无法删除!']);
               }
               if ($model->destroy(['id' => $ruleId]) !== FALSE) {
                //删除关联的角色拥有的权限
                    $rules=db('role')->select();
                        if ($rules) {
                          foreach ($rules as $key => $value) {
                         $rule=explode(',', $value['rules']);
                         $key=array_search($ruleId, $rule);
                              if ($key!==false) {
                                      array_splice($rule, $key, 1);
                                 }
                             $rule=implode($rule, ',');
                         db('role')->where(array('id'=>$value['id']))->update(['rules'=>$rule]);
                        }
                         setlog('Ruledel','Rule',session('user_auth.id'));
                  return  json(['code' => 1,'msg' => '权限删除成功']);
                        }
                  }
         }
  }

     
   /**
   *   查询权限
   * @param string  title权限名称,url权限规则
   * @return  json
   *
   */

   	public function search($keyword=null){
        	if($keyword){
                 if(($limit = input('limit')) && ($page = input('page'))){
                        $startLimit =  ($page-1)*$limit;
                        $info =collection(model('common/Rule')->where('title','like','%'.$keyword.'%')->whereOr('url','like','%'.$keyword.'%') ->limit($startLimit.','.$limit)->order('path')->select())->toArray();
                         }else{
                        $info =collection(model('common/Rule')->where('title','like','%'.$keyword.'%')->whereOr('url','like','%'.$keyword.'%')->order('path')->select())->toArray();
                      }
        	   }else{
                     if(($limit = input('limit')) && ($page = input('page'))){
                       $startLimit =  ($page-1)*$limit;
                       $info =collection(model('common/Rule')->order('path')->limit($startLimit.','.$limit)->select())->toArray();
                     }else{
                       $info =collection(model('common/Rule')->order('path')->select())->toArray();
                     }
                  }
          	
    	    //总数
	      $count = count($info); 
              foreach ($info as $key => $value) { 
                    $a = $value['level']?'|':'';
                    $b = str_repeat('---',$value['level']);
                    $info[$key]['title'] = $a.$b.$value['title'];
            }
           if (empty($info) && $count == 0) {
         	    return json(['code'=>0,'msg'=>'没有找到权限']);
       	} 
       	
           if ($count > 0){
       		return json(['code'=>1,'msg'=>'权限信息','count'=>$count,'data'=>$info]);
       	}
      }
}